﻿
using System.IO;
using System.Reflection;
using System.Web;

namespace MVCms.Core.PluginProvider
{
    public class AssemblyResourceVirtualFile : System.Web.Hosting.VirtualFile
    {
        private string path;

        /// <summary>
        /// Initializes a new instance of the <see cref="AssemblyResourceVirtualFile"/> class.
        /// </summary>
        /// <param name="virtualPath">The virtual path to the resource represented by this instance.</param>
        public AssemblyResourceVirtualFile(string virtualPath): base(virtualPath)
        {
            path = VirtualPathUtility.ToAppRelative(virtualPath);
        }

        /// <summary>
        /// When overridden in a derived class, returns a read-only stream to the virtual resource.
        /// </summary>
        /// <returns>A read-only stream to the virtual file.</returns>
        public override Stream Open()
        {
            string[] parts = path.Split('/');
            string assemblyName = parts[2];
            string resourceName = parts[3];

            assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
            byte[] assemblyBytes = File.ReadAllBytes(assemblyName);
            Assembly assembly = Assembly.Load(assemblyBytes);

            if (assembly != null)
                return assembly.GetManifestResourceStream(resourceName);

            return null;
        }
    }
}